package com.ukefu.webim.web.handler.api.rest;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.ukefu.core.UKDataContext;
import com.ukefu.util.Menu;
import com.ukefu.util.UKTools;
import com.ukefu.webim.service.repository.ExtentionRepository;
import com.ukefu.webim.service.repository.UserRepository;
import com.ukefu.webim.util.RestResult;
import com.ukefu.webim.util.RestResultType;
import com.ukefu.webim.web.handler.Handler;
import com.ukefu.webim.web.model.Extention;
import com.ukefu.webim.web.model.User;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/api/user")
@Api(value = "用户服务", description = "用户管理功能")
public class ApiUserController extends Handler{

	@Autowired
	private UserRepository userRepository;

	/**
	 * 返回用户列表，支持分页，分页参数为 p=1&ps=50，默认分页尺寸为 20条每页
	 * @param request
	 * @param username	搜索用户名，精确搜索
	 * @return
	 */
	@RequestMapping( method = RequestMethod.GET)
	@Menu(type = "apps" , subtype = "user" , access = true)
	@ApiOperation("返回用户列表，支持分页，分页参数为 p=1&ps=50，默认分页尺寸为 20条每页")
    public ResponseEntity<RestResult> list(HttpServletRequest request , @Valid String id ,@Valid String username) {
		Page<User> userList = null ;
		if(!StringUtils.isBlank(id)){
			userList = userRepository.findByIdAndOrgi(id, super.getOrgi(request), new PageRequest(super.getP(request), super.getPs(request))) ;
		}else{
			if(!StringUtils.isBlank(username)){
				userList = userRepository.findByDatastatusAndOrgiAndUsernameLike(false, super.getOrgi(request), username , new PageRequest(super.getP(request), super.getPs(request))) ;
			}else{
				userList = userRepository.findByDatastatusAndOrgi(false, super.getOrgi(request), new PageRequest(super.getP(request), super.getPs(request))) ;
			}
		}
        return new ResponseEntity<>(new RestResult(RestResultType.OK, userList), HttpStatus.OK);
    }
	
	/**
	 * 新增或修改用户用户 ，在修改用户信息的时候，如果用户 密码未改变，请设置为 NULL
	 * @param request
	 * @param user
	 * @return
	 */
	@RequestMapping(method = RequestMethod.PUT)
	@Menu(type = "apps" , subtype = "user" , access = true)
	@ApiOperation("新增或修改用户用户 ，在修改用户信息的时候，如果用户 密码未改变，请设置为 NULL")
    public ResponseEntity<RestResult> put(HttpServletRequest request , @Valid User user) {
    	if(user != null && !StringUtils.isBlank(user.getUsername())){
    		if(!StringUtils.isBlank(user.getPassword())){
	    		user.setPassword(UKTools.md5(user.getPassword()));
	    		userRepository.save(user) ;
    		}else if(!StringUtils.isBlank(user.getId())){
    			User old = userRepository.findByIdAndOrgi(user.getId(), super.getOrgi(request)) ;
    			user.setPassword(old.getPassword());
    			userRepository.save(user) ;
    		}
    		
    		
    	}
        return new ResponseEntity<>(new RestResult(RestResultType.OK), HttpStatus.OK);
    }
	
	/**
	 * 删除用户，只提供 按照用户ID删除 ， 并且，不能删除系统管理员
	 * @param request
	 * @param id
	 * @return
	 */
	@RequestMapping(method = RequestMethod.DELETE)
	@Menu(type = "apps" , subtype = "user" , access = true)
	@ApiOperation("删除用户，只提供 按照用户ID删除 ， 并且，不能删除系统管理员")
    public ResponseEntity<RestResult> delete(HttpServletRequest request , @Valid String id) {
		RestResult result = new RestResult(RestResultType.OK) ; 
    	User user = null ;
    	if(!StringUtils.isBlank(id)){
    		user = userRepository.findByIdAndOrgi(id, super.getOrgi(request)) ;
    		if(!user.getUsertype().equals("0")){	//系统管理员， 不允许 使用 接口删除
    			userRepository.delete(user);
    		}else{
    			result.setStatus(RestResultType.USER_DELETE);
    		}
    	}
        return new ResponseEntity<>(result, HttpStatus.OK);
    }
	

	@RequestMapping(value = "/saveuser")
	@Menu(type = "apps" , subtype = "user" , access = true)
	@ApiOperation("多字段新增或修改用户 ,修改用户时，用户ID、用户名、开关项以及数值的字段必须传，否则修改后会置为默认值；新增用户，用户名和密码必须传；")
    public ResponseEntity<RestResult> editUser(HttpServletRequest request , @RequestBody User user) {
		String msg = null ;
    	if(user != null && !StringUtils.isBlank(user.getUsername())){
    		
    		if(!StringUtils.isBlank(user.getId())){
    			//修改
    			User tempUser = userRepository.findByIdAndOrgi(user.getId() , super.getOrgi(request)) ;
    	    	if(tempUser != null && !StringUtils.isBlank(user.getUsername())){
    	    		
    	    		msg = validUserUpdate(user, tempUser);
    	    		if(StringUtils.isBlank(msg)){
    	    				
    	    			ExtentionRepository extentionRes = UKDataContext.getContext().getBean(ExtentionRepository.class);
    	    			
    	    			if(!StringUtils.isBlank(user.getUname())){
    	    				tempUser.setUname(user.getUname());
    	    			}
    	    			tempUser.setUsername(user.getUsername());
    	    			if(!StringUtils.isBlank(user.getEmail())){
    	    				tempUser.setEmail(user.getEmail());
    	    			}
    	    			if(!StringUtils.isBlank(user.getMobile())){
    	    				tempUser.setMobile(user.getMobile());
    	    			}
    	    			
    	    			tempUser.setMaxuser(user.getMaxuser());
    	    			
    	    			if(!StringUtils.isBlank(tempUser.getExtid())) {
    	    				Extention tempExtention = extentionRes.findByIdAndOrgi(tempUser.getExtid(), super.getOrgi(request)) ;
    	    				if(tempExtention!=null) {
    	    					tempExtention.setUserid(null);
    	    					tempExtention.setUsername(null);
    	    					tempExtention.setUname(null);
    	    					extentionRes.save(tempExtention) ;
    	    				}
    	    			}
    	    			
    	    			if(!StringUtils.isBlank(user.getExtid())) {
    	    				List<User> userList = userRepository.findByOrgiAndExtidAndDatastatus(super.getOrgi(request) , user.getExtid() , false) ;
    	    				Extention extention = extentionRes.findByIdAndOrgi(user.getExtid(), super.getOrgi(request)) ;
    	    				if(extention!=null && (userList.size() == 0 || userList.get(0).getId().equals(tempUser.getId()))) {
    	    					tempUser.setExtno(extention.getExtention());
    	    					extention.setUserid(tempUser.getId());
    	    					extention.setUsername(tempUser.getUsername());
    	    					extention.setUname(tempUser.getUname());
    	    					
    	    					extentionRes.save(extention) ;
    	    					
    	    					tempUser.setBindext(user.isBindext());
    	    					if(!StringUtils.isBlank(user.getHostid())){
    	    						tempUser.setHostid(user.getHostid());
    	    					}
    	    					if(!StringUtils.isBlank(user.getExtid())){
    	    						tempUser.setExtid(user.getExtid());
    	    					}
    	    					tempUser.setExtno(extention.getExtention());
    	    				}else {
    	    					msg = "ext_exist" ;
    	    				}
    	    			}
    	    			
    	    			
    	    			tempUser.setAgent(user.isAgent());
    	    			
    	    			tempUser.setCallcenter(user.isCallcenter());
    	    			
    	    			if(!StringUtils.isBlank(user.getPassword())){
    	    				tempUser.setPassword(UKTools.md5(user.getPassword()));
    	    			}
    	    			//是否是第二租户，除超级管理员所在租户下的其他租户
    	    			if(!tempUser.isSuperuser()) {
    	    				if(request.getParameter("admin")!=null && super.getUser(request).isSuperuser()){
    	    					tempUser.setUsertype("0");
    	    				}else{
    	    					tempUser.setUsertype(null);
    	    				}
    	    			}
    	    			
    	    			tempUser.setUpdatetime(new Date());
    	    			if(!StringUtils.isBlank(user.getLanguage())){
    	    				tempUser.setLanguage(user.getLanguage());
    	    			}
    	    			userRepository.save(tempUser) ;
    	    		}
    	    		
    	    	}
    		}else{
    			//新增
    			if(!StringUtils.isBlank(user.getPassword())){
    				msg = validUser(user);
    				if(StringUtils.isBlank(msg)){
    					user.setPassword(UKTools.md5(user.getPassword()));
    					userRepository.save(user) ;
    				}
        		}
    		}
    	}
        return new ResponseEntity<>(new RestResult(RestResultType.OK ,msg), HttpStatus.OK);
    }
	
	private String validUser(User user) {
    	String msg = "";
    	User tempUser = userRepository.findByUsernameAndDatastatus(user.getUsername(),false) ;
    	if(tempUser!=null) {
    		msg = "用户名已存在！";
    		return msg;
    	}
    	tempUser = userRepository.findByEmailAndDatastatus(user.getEmail(),false) ;
    	if(tempUser!=null) {
    		msg = "邮箱已存在！";
    		return msg;
    	}
    	tempUser = userRepository.findByMobileAndDatastatus(user.getMobile(),false) ;
    	if(tempUser!=null) {
    		msg = "手机号已存在！";
    		return msg;
    	}
    	return msg;
    }
	
	 private String validUserUpdate(User user,User oldUser) {
	    	String msg = "";
	    	User tempUser = userRepository.findByUsernameAndDatastatus(user.getUsername(),false) ;
	    	if(tempUser!=null&&!user.getUsername().equals(oldUser.getUsername())) {
	    		msg = "用户名已存在！";
	    		return msg;
	    	}
	    	tempUser = userRepository.findByEmailAndDatastatus(user.getEmail(),false) ;
	    	if(tempUser!=null&&!user.getEmail().equals(oldUser.getEmail())) {
	    		msg = "邮箱已存在！";
	    		return msg;
	    	}
	    	tempUser = userRepository.findByMobileAndDatastatus(user.getMobile(),false) ;
	    	if(tempUser!=null&&!user.getMobile().equals(oldUser.getMobile())) {
	    		msg = "手机号已存在！";
	    		return msg;
	    	}
	    	return msg;
	    }
	
	@RequestMapping(method = RequestMethod.POST)
	@Menu(type = "apps" , subtype = "user" , access = true)
	@ApiOperation("只修改用户密码")
    public ResponseEntity<RestResult> editPassword(HttpServletRequest request , @Valid User user) {
    	if(user != null &&!StringUtils.isBlank(user.getId()) && !StringUtils.isBlank(user.getPassword())){
    		User old = userRepository.findByIdAndOrgi(user.getId(), super.getOrgi(request)) ;
    		old.setPassword(UKTools.md5(user.getPassword()));
    		userRepository.save(old) ;
    	}
        return new ResponseEntity<>(new RestResult(RestResultType.OK), HttpStatus.OK);
    }
}